<template>
  <div class="plan-manager-page">
    <div>
      <FileContentSearchHeader
        :searchList="['mediaName']"
        :need-list="['search', 'addButton', 'delete']"
        @addNewFold="addNewFold"
        add-button-text="添加"
        @startUploadFile="startUploadFile"
        @changeSearch="changeSearchMethods"
        @mutiSendFile="mutiSendFileMethods"
        @mutiDel="mutiSceneDelHandler"
      >
        <el-input
          slot="media-input"
          placeholder="搜索计划"
          suffix-icon="el-search"
          @keyup.native.enter="inputSearch"
          v-model="searchObj.title">
        </el-input>
      </FileContentSearchHeader>
    </div>

    <CommonTable
      class="commonTable"
      ref="planListRef"
      :is-selection="true"
      :is-show-index="true"
      :is-has-opera="true"
      :t-column-data="planCol"
      :remote-api="getPlan"
      :query-params="searchObj"
      :is-reserve-select="true"
      @changeRow="changeRowMethods"
    >
      <template slot="type_value" slot-scope="scope">
        <div>
          {{transformTypeValue(scope.row)}}
        </div>
      </template>

      <template slot="operate" slot-scope="scope" class="operate-btn">
        <el-button type="text" @click="editPlan(scope.row)">编辑</el-button>
        <el-button type="text" @click="startPlan(scope.row)">执行</el-button>
        <el-button type="text" class="del-button" @click="showDelWarn(scope.row)">删除</el-button>
      </template>
    </CommonTable>


    <el-dialog
      title="提示"
      :visible.sync="isShowPlan"
      width="60%"
      :before-close="handleClose">
      <div>
        <el-steps :space="200" align-center :active="steps" finish-status="success">
          <el-step title="选择时间"></el-step>
          <el-step title="选择场景"></el-step>
          <el-step title="创建计划"></el-step>
        </el-steps>

        <el-form v-if="steps == 1" style="margin-top: 15px;" label-position="left" ref="form" :model="planForm" label-width="100px">
          <el-form-item label="时间">
            <el-time-picker
              value-format="HH:mm:ss"
              v-model="planForm.time"
              placeholder="请选择时间">
            </el-time-picker>
          </el-form-item>

          <el-form-item label="循环条件">
            <el-select v-model="planForm.type" placeholder="请选择">
              <el-option
                v-for="item in [{label: '每天', value: 1}, {label: '每周', value: 2}, {label: '每月', value: 3}, {label: '每年', value: 4}, {label: '指定日期', value: 5}]"
                :key="item.value"
                :label="item.label"
                :value="item.value">
              </el-option>
            </el-select>
          </el-form-item>

          <el-form-item label="">
            <!--每周-->
            <el-checkbox-group v-if="planForm.type == 2" v-model="weekValue">
              <el-checkbox label="1">周一</el-checkbox>
              <el-checkbox label="2">周二</el-checkbox>
              <el-checkbox label="3">周三</el-checkbox>
              <el-checkbox label="4">周四</el-checkbox>
              <el-checkbox label="5">周五</el-checkbox>
              <el-checkbox label="6">周六</el-checkbox>
              <el-checkbox label="7">周日</el-checkbox>
            </el-checkbox-group>

            <!--每月每日-->
            <el-select v-if="planForm.type == 3" v-model="monthDay" placeholder="请选择">
              <el-option
                v-for="item in dayList"
                :key="item.value"
                :label="item.label"
                :value="item.value">
              </el-option>
            </el-select>

            <!--每年几月几号-->
            <el-row :gutter="10" v-if="planForm.type == 4">
              <el-col :span="3">
                <el-select v-model="yearMonth" placeholder="请选择">
                  <el-option
                    v-for="item in monthList"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value">
                  </el-option>
                </el-select>
              </el-col>
              <el-col :span="3">
                <el-select v-model="yearDay" placeholder="请选择">
                  <el-option
                    v-for="item in dayList"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value">
                  </el-option>
                </el-select>
              </el-col>
            </el-row>

            <!--指定日期-->
            <el-row :gutter="10" v-if="planForm.type == 5">
              <el-col :span="10">
                <el-date-picker
                  v-model="appointDate"
                  type="date"
                  value-format="yyyy-MM-dd"
                  placeholder="选择日期">
                </el-date-picker>
              </el-col>
            </el-row>
          </el-form-item>
        </el-form>
        <CommonTable
          v-show="steps == 2"
          class="commonTable"
          ref="sceneTableRef"
          :is-selection="true"
          :is-show-index="true"
          :is-has-opera="false"
          :t-column-data="sceneCol"
          :remote-api="getSceneList"
          :query-params="searchSceneObj"
          :is-reserve-select="true"
          @changeRow="changeSceneRowMethods"
        >
          <template slot="log_content" slot-scope="scope">
            {{scope.row.title}}
          </template>
        </CommonTable>

        <el-form v-if="steps == 3" style="margin-top: 15px;" label-position="left" ref="form" :model="planForm" label-width="100px">
          <el-form-item label="任务名称">
            <el-input type="text" v-model="taskName"></el-input>
          </el-form-item>
        </el-form>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="handleClose">取 消</el-button>
        <el-button v-if="steps != 1" type="primary" @click="prePlan">上一步</el-button>
        <el-button v-if="steps == 1 || steps == 2" type="primary" @click="confirmCreatePlan">下一步</el-button>
        <el-button v-else type="primary" @click="finishCreate">确 定</el-button>
      </span>
    </el-dialog>
    <WarnPanelDialog
      :statusProp="statusIsDelFileProp"
      warn-content="是否删除计划"
      @confirmHandler="confirmDelMethods"
      @cancelHandler="cancelHandler"
    >
    </WarnPanelDialog>
  </div>
</template>

<script>
import FileContentSearchHeader from '@/components/FileContentSearchHeader'
import {planCol} from './tableCol/planCol'
import {sceneCol} from './tableCol/sceneCol'
import * as service from './service'
import * as sceneService from '../scene/service'
export default {
  components: {
    FileContentSearchHeader
  },
  data() {
    return {
      selectSceneStatus: false,
      delRows: [],
      sceneCol,
      planYear: '',
      planMonth: '',
      planDay: '',
      steps: 1,
      dayList: [],
      monthList: [],
      monthDay: '',
      weekValue: [],
      appointDate: '',
      isShowPlan: false,
      getSceneList: sceneService.getWindowScene,
      sceneList: [],
      isEdit: false,
      searchObj: {
        title: '',
        page: 1,
        pageSize: 20
      },
      taskName: '',
      searchSceneObj: {
        type: 1,
        page: 1,
        pageSize: 20
      },
      yearMonth: '',
      yearDay: '',
      planForm: {
        sceneIds: [],
        title: '',
        type: '',
        typeValue: '',
        time: '',
        date: '',
        id: null
      },
      selectScene: [],
      planCol,
      getPlan: service.planList,
      clickCache: {},
      statusIsDelFileProp: false
    }
  },
  computed: {
    transformTypeValue() {
      return (row) => {
        //类型 1每天 2每周 3每月 4每年 5指定日期
        if(row.type == 1) {
          return "每天";
        } else if(row.type == 2) {
          let str = "每周";
          let value = row.type_value;
          if(value.indexOf(",") > -1) {
            let valueArr = value.split(",");
            let index = 1;
            valueArr.forEach( (item) => {
              if(index == valueArr.length) {
                str = str + this.getWeek(item);
              } else {
                str = str + this.getWeek(item) + "、";
              }
              index++;
            })
          } else {
            str = str + this.getWeek(value);
          }
          return str;
        } else if(row.type == 3) {
          return `每月${row.type_value}日`
        } else if(row.type == 4) {
          return `每年${row.type_value}`
        } else if(row.type == 5) {
          return `${row.type_value}`
        }
      }
    }
  },
  mounted() {
    this.monthList = []
    for(let i = 1;i < 13;i++) {
      this.monthList.push({
        label: `${i}月`,
        value: i.toString().padStart(2, '0')
      })
    }
    this.dayList = []
    for(let i = 1;i < 32;i++) {
      this.dayList.push({
        label: `${i}日`,
        value: i.toString().padStart(2, '0')
      })
    }
    this.getList();

      let data = {
        "page" : 1,
        "pageSize" : 100000,
        "type" : 1
      }
      this.getSceneList(data).then((res) => {
        this.sceneList = res.data.records
      })
  },
  methods: {
    getWeek(val) {
      if(val == 1) {
        return "一";
      } else if(val == 2) {
        return "二";
      }  else if(val == 3) {
        return "三";
      }  else if(val == 4) {
        return "四";
      }  else if(val == 5) {
        return "五";
      }  else if(val == 6) {
        return "六";
      }  else if(val == 7) {
        return "日";
      }
    },
    inputSearch() {
      this.getList()
    },
    confirmDelMethods() {
      const params = {
        ids: []
      }
      if(this.delRows.length === 0) {
        params.ids = [this.clickCache.id]
      } else {
        params.ids = this.delRows.map(item => item.id)
      }

      service.deletePlan(params).then((res) => {
        this.$message.success('删除成功')
        this.cancelHandler()
        this.getList()
      })
    },
    cancelHandler() {
      this.clickCache = {}
      this.statusIsDelFileProp = false
    },
    showDelWarn(row) {
      this.clickCache = Object.assign({}, row)
      this.statusIsDelFileProp = true
    },
    startPlan(row) {
      const params = {
        planId: row.id
      }
      service.excutePlan(params).then((res) => {
        console.log('res.data ---', res)
        this.$message.success('执行成功')
      })
    },
    changeSceneRowMethods(row) {
      this.selectScene = [...row]
    },
    finishCreate() {
      const params = {
        sceneIds: [],
        title: this.taskName,
        time: this.planForm.time,
        type: this.planForm.type,
        id: this.planForm.id
      }

      this.selectScene.forEach((item) => {
        params.sceneIds.push(item.id)
      })
      if(params.type == 2) {
        params.typeValue = this.weekValue.join(',')
      } else if(params.type == 3) {
        params.typeValue = this.monthDay
      } else if(params.type == 4) {
        params.typeValue = `${this.yearMonth}-${this.yearDay}`
      } else if(params.type == 5) {
        params.typeValue = this.appointDate
      }

      service.createPlan(params).then((res) => {
        console.log('res.data ---', res)
        this.$message.success('创建成功')
        this.getList()
        this.handleClose()
      })
    },
    prePlan() {
      this.steps = this.steps - 1;
    },
    confirmCreatePlan() {
      console.log('steps ---', this.steps)
      if(this.steps == 1) {
        if(this.planForm.time == '') {
          this.$message.error('请选择时间')
          return
        }
        if(this.planForm.type == '') {
          this.$message.error('请选择循环条件')
          return
        }
        if(this.planForm.type == 2) {
          if(this.weekValue.length === 0) {
            this.$message.error('请选择条件')
            return
          }
        } else if(this.planForm.type == 3) {
          if(this.monthDay == ''){
            this.$message.error('请选择条件')
            return
          }
        } else if(this.planForm.type == 4) {
          if(this.yearMonth== '' || this.yearDay == '') {
            this.$message.error('请选择条件')
            return
          }
        } else if(this.planForm.type == 5) {
          if(this.appointDate == '') {
            this.$message.error('请选择条件')
            return
          }
        }
      } else if(this.steps == 2) {
        if(this.selectScene.length === 0) {
          this.$message.error('请选择场景')
          return
        }
      }

      this.steps = this.steps + 1
      if(this.steps == 2) {
        if(this.isEdit) {
          this.toggleSceneSelection();
        } else {
          this.$refs.sceneTableRef.clearSelectionMethods()
        }
        this.$nextTick(() => {
          const params = Object.assign({}, this.searchSceneObj)
          this.$refs.sceneTableRef.queryData(params)
        })
      }
    },
    toggleSceneSelection(){
      if(!this.selectSceneStatus) {
        setTimeout(() => {
          this.toggleSceneSelection();
        }, 100)
      } else {
        this.$refs.sceneTableRef.toggleRowSelectionMethods(this.selectScene);
      }
    },
    handleClose() {
      this.steps = 1
      this.isShowPlan = false
    },
    getList() {
      const params = Object.assign({}, this.searchObj)
      this.$refs.planListRef.queryData(params)
    },
    changeRowMethods(row) {
      this.delRows = [...row]
    },
    addNewFold() {
    },
    startUploadFile() {
      this.isEdit = false;
      this.planForm = {
        sceneIds: [],
        title: '',
        type: '',
        typeValue: '',
        time: '',
        date: ''
      }
      this.type_value = '';
      this.yearMonth = '';
      this.yearDay = '';
      this.monthDay = '';
      this.isShowPlan = true
      this.selectScene = [];
      this.weekValue = [];
      this.taskName = '';
      this.appointDate = '';
    },
    editPlan(row) {
      this.isEdit = true;
      this.isShowPlan = true;
      this.planForm = {
        sceneIds: row.scene_ids,
        title: row.title,
        type: row.type,
        typeValue: row.type_value,
        time: row.time,
        id: row.id
      }
      this.taskName = row.title;
      if(row.type  == 4) {
        this.yearMonth = row.type_value.split("-")[0];
        this.yearDay = row.type_value.split("-")[1];
      } else if(row.type  == 3){
        this.monthDay  = row.type_value;
      } else if(row.type == 5) {
        this.appointDate = row.type_value;
      } else if(row.type == 2) {
        if(row.type_value.indexOf(",") > -1) {
          this.weekValue = row.type_value.split(",");
        } else {
          this.weekValue =[row.type_value]
        }
      }

      this.selectSceneStatus = false;
      this.selectScene = [];
      for(let i = 0; i < row.scene_ids.length; i++) {
        for(let j = 0; j < this.sceneList.length; j++) {
          if(this.sceneList[j].id == row.scene_ids[i]){
            this.selectScene.push(this.sceneList[j])
          }
        }
      }
      this.selectSceneStatus = true;
    },
    changeSearchMethods() {
      this.getList()
    },
    mutiSendFileMethods() {

    },
    mutiSceneDelHandler() {
      if(this.delRows.length === 0) {
        this.$message.error('请选择删除的计划')
        return
      }
      this.statusIsDelFileProp = true
    }
  }
}
</script>

<style scoped lang="scss">
  .plan-manager-page{
    padding: 15px;
    background: white;

    .commonTable{
      margin-top: 15px;
    }
  }
</style>
